package sz.szsmk.citizencard.ui.dzsmkavtivity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import android.text.Editable;
import android.text.Html;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.util.List;

import javax.inject.Inject;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.dialog.ChooseCardDialog;
import sz.szsmk.citizencard.model.network.bean.response.AdvertisementsRes;
import sz.szsmk.citizencard.model.network.dzbean.res.AuthenticationResp;
import sz.szsmk.citizencard.model.network.dzbean.res.Bank;
import sz.szsmk.citizencard.model.network.dzbean.res.BaseRes;
import sz.szsmk.citizencard.model.network.dzbean.res.GetJobRes;
import sz.szsmk.citizencard.model.network.dzbean.res.GetPeopleRes;
import sz.szsmk.citizencard.model.network.dzbean.res.GetUserInfoRes;
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent;
import sz.szsmk.citizencard.model.network.dzbean.res.PreAuthResult;
import sz.szsmk.citizencard.mvp.BasePresenter;
import sz.szsmk.citizencard.mvp.PersonInfoQueryMvpView;
import sz.szsmk.citizencard.mvp.RealNameAuthenticationMvpView;
import sz.szsmk.citizencard.mvp.dzsmkpresenter.RealNameAuthenticationPresenter;
import sz.szsmk.citizencard.mvp.dzsmkpresenter.RealPresenter;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.util.SmsTimer;
import sz.szsmk.citizencard.widget.GlobalVariables;

/**
 * Created by yangzhengwen on 2017/10/1.
 */
public class BindBankCardOldActivity extends AppBaseActivity implements
        RealNameAuthenticationMvpView, PersonInfoQueryMvpView, View.OnClickListener {

    TextView tv_qr_name;
    TextView tv_qr_id;
    EditText et_qr_bank_card;
    TextView tv_qr_bank_name;
    EditText et_qr_phone_number;
    EditText et_qr_phone_pin;
    TextView tv_qr_get_pin;

    @Inject
    RealNameAuthenticationPresenter realNameAuthenticationPresenter;
    @Inject
    RealPresenter realPresenter;

    private int type;
    private String name;
    private String iccard;
    private String bankCode;
    private SmsTimer smsTimer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getComponent().inject(this);
        setContentView(R.layout.qr_activity_bind_bank_card);


        tv_qr_name = findViewById(R.id.tv_qr_name);
        tv_qr_id = findViewById(R.id.tv_qr_id);
        et_qr_bank_card = findViewById(R.id.et_qr_bank_card);
        tv_qr_bank_name = findViewById(R.id.tv_qr_bank_name);
        et_qr_phone_number = findViewById(R.id.et_qr_phone_number);
        et_qr_phone_pin = findViewById(R.id.et_qr_phone_pin);
        tv_qr_get_pin = findViewById(R.id.tv_qr_get_pin);
        tv_qr_get_pin.setOnClickListener(this);


        findViewById(R.id.tv_qr_banklist).setOnClickListener(this);

        findViewById(R.id.tv_qr_bind).setOnClickListener(this);





        tv_qr_bank_name.setHint(Html.fromHtml("开户行名称（<font color='#EB5659'>仅支持工、农、中、建4大行</font>）"));

        if (type == 1) {
            realPresenter.getPersonInfo();
        } else if (type == 0) {
//            tv_qr_name.setText(name + "");
//            tv_qr_id.setText(iccard + "");
            realPresenter.getPersonInfo();
        }
        bankCardNumAddSpace(et_qr_bank_card, null);
        smsTimer = new SmsTimer(60000, 1000, tv_qr_get_pin);

        et_qr_bank_card.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus && !TextUtils.isEmpty(et_qr_bank_card.getText())) {
                    realNameAuthenticationPresenter.getBankName(parseCardNo(et_qr_bank_card.getText().toString()));
                }
            }
        });

        et_qr_bank_card.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mHandler.hasMessages(MSG_GET_BANK_NAME)) {
                    mHandler.removeMessages(MSG_GET_BANK_NAME);
                }
                //延时发送请求
                if (parseCardNo(et_qr_bank_card.getText().toString()).length() == 14) {
                    mHandler.sendEmptyMessageDelayed(MSG_GET_BANK_NAME, 800);
                }
                if (s.toString().length() == 0) {
                    tv_qr_bank_name.setText("");
                }

            }
        });
    }

    @Override
    public void onGainPersonInfo(GetUserInfoRes user) {
        tv_qr_name.setText(user.getData().getRealName());
        tv_qr_id.setText(user.getData().getIdCardNumber());
    }

    @Override
    public void getAdvertisementsResult(AdvertisementsRes advertisementsRes) {

    }

    private static final int MSG_GET_BANK_NAME = 0x01;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_GET_BANK_NAME:
                    realNameAuthenticationPresenter.getBankName(parseCardNo(et_qr_bank_card.getText().toString()));
                    break;
            }
        }
    };

    private String parseCardNo(String cardNo) {
        return cardNo.replaceAll(" ", "");
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            int x = (int) ev.getX();
            int y = (int) ev.getY();
            if (v.getId() == R.id.et_qr_bank_card && !isInViewZone(v, x, y)) {
                if (!TextUtils.isEmpty(et_qr_bank_card.getText())) {
                    realNameAuthenticationPresenter.getBankName(parseCardNo(et_qr_bank_card.getText().toString()));
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean isInViewZone(View view, int x, int y) {
        Rect rect = new Rect();
        view.getDrawingRect(rect);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        rect.left = location[0];
        rect.top = location[1];
        rect.right = rect.right + location[0];
        rect.bottom = rect.bottom + location[1];
        return rect.contains(x, y);
    }

    @Override
    protected BasePresenter[] initPresenters() {
        return new BasePresenter[]{realNameAuthenticationPresenter, realPresenter};
    }


    public void onClickView(View v) {
        String name = tv_qr_name.getText().toString().trim();
        String cardId = tv_qr_id.getText().toString().trim();
        String re = et_qr_bank_card.getText().toString().trim();
        String etBank = re.replace(" ", "");
        if (v.getId() == R.id.tv_qr_get_pin) {

            if (TextUtils.isEmpty(name)) {
                PubUtils.popTipOrWarn(BindBankCardOldActivity.this, "请输入姓名");
                return;
            }
            if (TextUtils.isEmpty(cardId)) {
                PubUtils.popTipOrWarn(BindBankCardOldActivity.this, "请输入身份证号");
                return;
            }
            if (TextUtils.isEmpty(etBank)) {
                PubUtils.popTipOrWarn(BindBankCardOldActivity.this, "请输入您的银行卡号");
                return;
            }

            if (!TextUtils.isEmpty(et_qr_phone_number.getText())) {
                String channelId = ACache.get(this).getAsString("channelId");
                if (channelId.equals("000001")) {
                    realNameAuthenticationPresenter.getCheckCode(et_qr_phone_number.getText().toString(), type);
                } else {
                    realNameAuthenticationPresenter.getCheckCodeCcbReq(etBank, cardId, et_qr_phone_number.getText().toString().trim(), name);
                }

            } else {
                PubUtils.popTipOrWarn(BindBankCardOldActivity.this, "请输入银行预留的手机号");
            }
        } else if (v.getId() == R.id.tv_qr_banklist) {
            Intent bankListIntent = new Intent(BindBankCardOldActivity.this, SupportBankListActivity.class);
            startActivity(bankListIntent);
        } else if (v.getId() == R.id.tv_qr_bind) {
            if (checkDouble()) {
                return;
            }

            if (type == 0) {
//                realNameAuthenticationPresenter.realNameAuthentication(bankCode, tv_qr_name.getText().toString().trim(),
//                        tv_qr_id.getText().toString().trim(), parseCardNo(et_qr_bank_card.getText().toString()),
//                        et_qr_phone_number.getText().toString().trim(), et_qr_phone_pin.getText().toString().trim());
                showLoadingDialog();
                realNameAuthenticationPresenter.changeMyBankCard(bankCode, parseCardNo(et_qr_bank_card.getText().toString()),
                        et_qr_phone_number.getText().toString().trim(), et_qr_phone_pin.getText().toString().trim());

//
            } else {
                showLoadingDialog();
                realNameAuthenticationPresenter.changeMyBankCard(bankCode, parseCardNo(et_qr_bank_card.getText().toString()),
                        et_qr_phone_number.getText().toString().trim(), et_qr_phone_pin.getText().toString().trim());
            }
        }
    }

    private long time = 0;

    private boolean checkDouble() {
        if (System.currentTimeMillis() - time < 2000) {
            time = System.currentTimeMillis();
            return true;
        } else {
            time = System.currentTimeMillis();
            return false;
        }


    }

    @Override
    public void onAuthenticationSuccess() {
        dismissLoadingDialog();
        PreAuthResult preAuthResult = GlobalVariables.getInstance(this).getPreAuthResult();
        if (type == 0) {

            preAuthResult.setUserStatus(Constant.QUERY_QR_RESULT_NO_PAY_PWD_SET);
        } else {
//            preAuthResult.setUserStatus(Constant.QUERY_QR_RESULT_NO_PAY_PWD_SET);
        }
        GlobalVariables.getInstance(this).setPreAuthResult(this, preAuthResult);
        showResult(true);
    }

    @Override
    public void onAuthenticationSuccess(AuthenticationResp authenticationResp) {
        dismissLoadingDialog();
        if ("0000".equals(authenticationResp.getCode())) {
            PreAuthResult preAuthResult = GlobalVariables.getInstance(this).getPreAuthResult();
            preAuthResult.setUserStatus(Constant.QUERY_QR_RESULT_NO_PAY_PWD_SET);
            GlobalVariables.getInstance(this).setPreAuthResult(this, preAuthResult);
            showResult(true);
        } else if ("0046".equals(authenticationResp.getCode())) {
            ChooseCardDialog dialog = new ChooseCardDialog(BindBankCardOldActivity.this);
            dialog.setOldBankNo(authenticationResp.getOldBankNo());
            dialog.setNewBankNo(authenticationResp.getnBankNo());
            dialog.setOnBindCardCheckListener(new ChooseCardDialog.OnBindCardCheckListener() {
                @Override
                public void onBindCheck(int type) {
                    showLoadingDialog();
                    realNameAuthenticationPresenter.oldUserCheck(type);
                }
            });
            dialog.show();
        }
    }

    @Override
    public void onChangeBankCard() {
        showResult(true);
    }

    @Override
    public void onAuthenticationFail(String message) {
        dismissLoadingDialog();
        showResult(false);
    }

    private PopupWindow popupWindow;

    private void showResult(final boolean success) {
        View popView = getLayoutInflater().inflate(R.layout.qr_pop_authentication_result, null);
        TextView tv_qr_ok = (TextView) popView.findViewById(R.id.tv_qr_ok);
        ImageView iv_qr_authentication_status = (ImageView) popView.findViewById(R.id.iv_qr_authentication_status);
        TextView tv_qr_authentication_message = (TextView) popView.findViewById(R.id.tv_qr_authentication_message);
        if (success) {
            iv_qr_authentication_status.setImageResource(R.drawable.qr_authentication_successful);
            tv_qr_authentication_message.setText("更换／绑卡成功");
        } else {
            iv_qr_authentication_status.setImageResource(R.drawable.qr_authentication_failed);
            tv_qr_authentication_message.setText("更换／绑卡失败");
        }
        popupWindow = new PopupWindow(popView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);//popView即popupWindow的布局，ture设置focusAble.

        //必须设置BackgroundDrawable后setOutsideTouchable(true)才会有效。这里在XML中定义背景，所以这里设置为null;
//        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
//        popupWindow.setOutsideTouchable(false); //点击外部关闭。
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);    //设置一个动画。
        backgroundAlpha(0.5f);
        popupWindow.showAtLocation(findViewById(R.id.ll_qr_bind_bank), Gravity.CENTER, 0, 0);
        tv_qr_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (success) {
                    setResult(456);
                    eventBus.post(new MessageEvent(MessageEvent.CODE_BIND_BANK_CARD_SUCCESS));
                    finish();
                } else {
//                    finish();
                }
            }
        });
        popupWindow.setOnDismissListener(new poponDismissListener());
    }

    @Override
    public void onClick(View v) {
        onClickView(v);
    }

    class poponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            backgroundAlpha(1f);
        }
    }


    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }


    @Override
    public void onGetCheckCode() {
        smsTimer.start();
    }

    @Override
    public void onGetCheckCodeFail(BaseRes baseRes) {

    }

    @Override
    public void onGetBankName(Bank bank) {
        tv_qr_bank_name.setText(bank.getBankName() + "");
        bankCode = bank.getBankCode();
    }

    @Override
    public void onGetBankNamefail() {

    }

    @Override
    public void onGetPeopleSucc(List<GetPeopleRes.DataBean> data) {

    }

    @Override
    public void onGetPeopleFail() {

    }

    @Override
    public void onGetJobSucc(List<GetJobRes.DataBean> data) {

    }

    @Override
    public void onGetJobFail() {

    }

    @Override
    protected CharSequence getTopTitle() {
        Intent intent = getIntent();
        type = intent.getIntExtra("type", 0);
        name = intent.getStringExtra("name");
        iccard = intent.getStringExtra("iccard");
        if (type == 0) {
            return getString(R.string.qr_bind_bank_card);
        } else {
            return "更换银行卡";

        }
    }

    private void bankCardNumAddSpace(final EditText mEditText, final TextView carSub_tv) {
        mEditText.addTextChangedListener(new TextWatcher() {

            int beforeTextLength = 0;
            int onTextLength = 0;
            boolean isChanged = false;

            int location = 0;// 记录光标的位置
            private char[] tempChar;
            private StringBuffer buffer = new StringBuffer();
            int konggeNumberB = 0;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeTextLength = s.length();
                if (buffer.length() > 0) {
                    buffer.delete(0, buffer.length());
                }
                konggeNumberB = 0;
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) == ' ') {
                        konggeNumberB++;
                    }
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                onTextLength = s.length();
                buffer.append(s.toString());
                if (onTextLength == beforeTextLength || onTextLength <= 3 || isChanged) {
                    isChanged = false;
                    return;
                }
                isChanged = true;
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (carSub_tv != null) {
                    carSub_tv.setText(mEditText.getText());
                }
                if (isChanged) {
                    location = mEditText.getSelectionEnd();
                    int index = 0;
                    while (index < buffer.length()) {
                        if (buffer.charAt(index) == ' ') {
                            buffer.deleteCharAt(index);
                        } else {
                            index++;
                        }
                    }

                    index = 0;
                    int konggeNumberC = 0;
                    while (index < buffer.length()) {
                        if ((index == 4 || index == 9 || index == 14 || index == 19 || index == 24 || index == 29)) {
                            buffer.insert(index, ' ');
                            konggeNumberC++;
                        }
                        index++;
                    }

                    if (konggeNumberC > konggeNumberB) {
                        location += (konggeNumberC - konggeNumberB);
                    }

                    tempChar = new char[buffer.length()];
                    buffer.getChars(0, buffer.length(), tempChar, 0);
                    String str = buffer.toString();
                    if (location > str.length()) {
                        location = str.length();
                    } else if (location < 0) {
                        location = 0;
                    }

                    if (str.length() >= 23) {
                        str = str.substring(0, 23);
                        location = str.length();
                    }

                    mEditText.setText(str);
                    Editable etable = mEditText.getText();
                    Selection.setSelection(etable, location);
                    isChanged = false;
                }
            }
        });
    }
}
